package com.ruoyi.order.utils;

import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.ip.IpUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * API访问统计切面
 */
@Aspect
@Component
public class ApiVisitAspect {

    @Pointcut("@annotation(com.ruoyi.common.annotation.ApiVisitLog)")
    public void apiVisitPointCut() {}

    @Before("apiVisitPointCut()")
    public void doBefore(JoinPoint joinPoint) {
        HttpServletRequest request = ServletUtils.getRequest();

        String apiKey = request.getHeader("X-API-KEY");
        String ip = IpUtils.getIpAddr(request);
        String uri = request.getRequestURI();
        String method = request.getMethod();
        Date visitTime = new Date();

        // 这里可以保存到数据库
        System.out.println(StringUtils.format("API访问记录 - Key: {}, IP: {}, URI: {}, Method: {}, Time: {}",
                apiKey, ip, uri, method, visitTime));
    }
}
